<template>
  <a-layout id="FormDesignIndex" class="container">
    <!--组件选择区-->
    <a-layout-sider :width="280">
      <item-select @dragClone="selectItem" />
    </a-layout-sider>
    <a-layout>
      <!--工具栏-->
      <a-layout-header>
        <tool-bar
          :form-list="formList"
          :form-config="formConfig"
          @select-item="selectItem"
        />
      </a-layout-header>
      <!--表单渲染-->
      <a-layout-content>
        <form-container
          v-model:list="formList"
          v-model:model="formModel"
          @select-item="selectItem"
          @delete-item="deleteItem"
        />
      </a-layout-content>
    </a-layout>
    <!--组件设置-->
    <a-layout-sider :width="340">
      <item-setting
        v-model:config="selected"
        v-model:form-config="formConfig"
      />
    </a-layout-sider>
  </a-layout>
</template>

<script lang="ts" setup>
import { ref, provide, getCurrentInstance, defineExpose } from 'vue';
import ToolBar from '@/components/form-design/tool-bar/index.vue';
import FormContainer from '@/components/form-design/form-container/index.vue';
import ItemSelect from '@/components/form-design/item-select/index.vue';
import ItemSetting from '@/components/form-design/item-setting/index.vue';
import { FormItemConfig } from '@/components/form-design/item-select/config/type';
import { cloneDeep } from 'lodash';

const proxy = getCurrentInstance();

// 表单配置项
const formConfig = ref({
  size: 'medium',
  layout: 'horizontal',
  labelAlign: 'left',
  labelColProps: {
    span: 5,
    offset: 0
  },
  wrapperColProps: {
    span: 19,
    offset: 0
  }
});
// 表单控件列表
const formList = ref<Array<FormItemConfig>>([]);
// 被选中的表单组件
const selected = ref<FormItemConfig>({
  id: '',
  config: {},
  name: '',
  group: '',
  type: '',
  component: '',
  settingComponent: ''
});
// 表单值
const formModel = ref({});

provide('selected', selected);
provide('formConfig', formConfig);
provide('formInstance', proxy);
provide('formType', 'design');
provide('formPermission', {});

const selectItem = (value: any) => {
  selected.value = value;
};

const deleteItem = (value: any) => {
  if (value.id === selected.value.id) {
    selected.value = {
      id: '',
      config: {},
      name: '',
      group: '',
      type: '',
      component: '',
      settingComponent: ''
    };
  }
};

const setConfig = (config: any, list: Array<FormItemConfig>) => {
  if (config) {
    formConfig.value = cloneDeep(config);
  }
  if (list) {
    formList.value = cloneDeep(list);
  }
};

const getConfig = () => {
  return {
    formConfig: formConfig.value,
    formList: formList.value
  };
};

defineExpose({
  setConfig,
  getConfig
});
</script>

<script lang="ts">
export default {
  name: 'FormDesign'
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
}
</style>